<template>
  <view class="station-details">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="电站详情"></van-nav-bar>
    <!-- #endif -->
    <view class="station-header">
      <!-- 电站名称 -->
      <view class="name">{{ data.items.stationName }}</view>
      <!-- 电站地址 -->
      <view class="address">
        <view class="iconfont icon-map"></view>
        <view class="text">{{ data.items.areaCodeName }}{{ data.items.address }}</view>
      </view>
      <!-- 桩数量 -->
      <view class="pile">
        <view class="pile-item">
          <view class="test1 test1-direct">直</view>
          <text class="test2 test2-direct">闲{{ data.items.countFreeConnectorDC }}</text>
          <text>/共{{ data.items.countConnectorDC }}</text>
        </view>
        <view class="pile-item item-interflow">
          <view class="test1 test1-interflow">交</view>
          <text class="test2 test2-interflow">闲{{ data.items.countFreeConnectorAC }}</text>
          <text>/共{{ data.items.countConnectorAC }}</text>
        </view>
      </view>
      <!-- 收藏 -->
      <view class="collect" @tap.stop="tapCollect(data.items)">
        <view
          class="iconfont"
          :class="[data.items.collectStatus ? 'icon-collect1' : 'icon-collect']"></view>
        <text class="text">收藏</text>
      </view>
      <!-- 定位 -->
      <view class="distance" @tap.stop="tapDistance(data.items)">
        <view class="iconfont icon-exclude"></view>
        <text class="text">
          {{ data.items.distance ? (data.items.distance / 1000).toFixed(1) : '--' }}km
        </text>
      </view>
      <!-- 标签 -->
      <view v-if="data.labelStr && data.labelStr.length > 0" class="labels">
        <view v-for="(temp, index) in data.labelStr" :key="index">
          <text v-if="index !== 0" class="line">|</text>
          <text class="label-item">{{ temp }}</text>
        </view>
      </view>
      <!-- 图片 -->
      <scroll-view scroll-x="true" class="pic-wrap" v-if="data.pics.length > 0">
        <image
          v-for="(item, index) in data.pics"
          :key="index"
          :src="item"
          class="pic"
          mode="scaleToFill"
          @tap="tapImage"></image>
      </scroll-view>
      <!-- 分割条 -->
      <view class="line"></view>
      <!-- tabs -->
      <view class="tabs-wrap">
        <view class="tab" :class="{ 'tab-active': data.tabActive === 1 }" @tap="tapTabs(1)">
          站点详情
        </view>
        <view class="tab" :class="{ 'tab-active': data.tabActive === 2 }" @tap="tapTabs(2)">
          终端列表
        </view>
        <view class="tab" :class="{ 'tab-active': data.tabActive === 3 }" @tap="tapTabs(3)">
          查看评价
        </view>
      </view>
    </view>

    <!-- tab-view -->
    <!-- 电站详情 -->
    <StatioinInfo
      id="statioin-info"
      v-if="data.tabActive === 1"
      :items="data.items"
      :styleHeight="data.tabHeight"></StatioinInfo>

    <!-- 终端列表 -->
    <QcscrollUni
      ref="scrollPileRef"
      v-if="data.tabActive === 2"
      :getData="getPile"
      :top="data.topScroll"
      :height="data.heightScroll"
      :bottom="data.bottomScroll">
      <view
        class="list-wrap"
        v-for="(item, index) in data.pileList"
        :key="index"
        @tap="tapPile(item)">
        <view class="pile-icon" :style="{ backgroundImage: `url(${getPileImg(item)})` }">
          <text v-if="item.soc" class="text1">
            {{ item.soc }}
            <text class="text2">%</text>
          </text>
        </view>
        <view class="flex-column pile-wrap">
          <view>终端名称：{{ item.connectorName }}</view>
          <view v-if="appType === 'lznt'" class="pile-info">
            <view class="textl">快捷码</view>
            <view class="textr">{{ item.shortcutCode }}</view>
          </view>
          <view class="pile-info">
            <view class="textl">电桩功率</view>
            <view class="textr">{{ item.power }}kW</view>
          </view>
          <view class="pile-info">
            <view class="textl">接口类型</view>
            <view class="textr">{{ item.typeName }}</view>
          </view>
          <view class="pile-info">
            <view class="textl">终端编码</view>
            <view class="textr">{{ item.connectorCode }}</view>
          </view>
        </view>
        <view class="list-line"></view>
        <view v-if="item.isAlonePrice" class="alone-price">单独定价</view>
      </view>
    </QcscrollUni>

    <!-- 评价 -->
    <QcscrollUni
      ref="scrollCommentRef"
      v-if="data.tabActive === 3"
      :getData="getComment"
      :top="data.topScroll"
      :height="data.heightScroll"
      :bottom="data.bottomScroll">
      <view class="list-wrap flex-column" v-for="(item, index) in data.commentList" :key="index">
        <view class="comment-info">
          <view class="textl text-bold">{{ item.userMobile }}</view>
          <view class="textr">{{ item.contentTime }}</view>
        </view>
        <view class="comment-msg comment-text">{{ item.content }}</view>
        <view v-if="item.reply" class="comment-reply comment-text">电站回复：{{ item.reply }}</view>
        <view class="list-line"></view>
      </view>
    </QcscrollUni>

    <!-- 底部按钮 -->
    <view class="bottom-wrap">
      <button class="bnt-wrap bnt" @tap="tapCode">扫码充电</button>
    </view>
    <PopupBtm ref="locationOpenRef" @set-item="chooseType" />
  </view>
</template>

<script lang="ts" setup>
import { getSystemInfo, getToken, getwv, setToastInstance, systemInfo } from '@mixins/info';
import StatioinInfo from './stationInfo.vue';
import QcscrollUni from '@/components/qcscroll/qcscrollUni.vue';
import { queryStationDetail, queryPileList, queryStationComment } from '@/service/apis/station';
import { getLocationInfo, openLocation } from '@/utils/location';
import { stationCollect } from '@pages/stationList/station';
import { handleCode } from '@/utils/util';
import PopupBtm from '@/components/popupBtm/popupBtm.vue';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const appType = import.meta.env.VITE_VUE_APP_TYPE;

const resUrl = import.meta.env.VITE_VUE_APP_RES;

const scrollPileRef = ref();

const data = reactive({
  id: '',
  items: {} as any,
  pics: [] as any,
  tabActive: 1,
  tabHeight: '', // 滚动区域高度
  topScroll: '', //滚动区域上距离
  heightScroll: '',
  bottomScroll: `${getSystemInfo().safeBottom > 0 ? '' : '124rpx'}`, //滚动区域下距离
  labelStr: [] as Array<string>, // 标签
  pileList: [] as any, // 终端列表
  commentList: [] as any, // 评论列表
  isLoad: false,
});

const locationOpenRef = ref();
const locationOpenItem = ref({} as any);

// 获取元素信息
const { proxy: vm } = getCurrentInstance()!;
const query = uni.createSelectorQuery().in(vm);
const getHeight = () => {
  query
    .selectAll('.station-header, #statioin-info, .bottom-wrap')
    .boundingClientRect((info: any) => {
      if (Array.isArray(info)) {
        if (info[0]?.height) {
          data.tabHeight = `height: calc(100% - ${Number(info[0].height)}px - 124rpx)`;
          // #ifdef H5
          data.tabHeight = `height: calc(100% - ${Number(info[0].height)}px - ${getwv(62)}px - ${
            systemInfo.navHeight
          }px)`;
          // #endif
          console.log('hhh11---', data.tabHeight);
        }
        if (data.tabActive === 1 && info[1]?.top) {
          console.log('info--1-', info[1].top, info[1]);
          data.topScroll = `${info[1].top}px`;
          // data.heightScroll = `${info[1].right}px`;
        }
        if (info[2]) {
          if (getSystemInfo().safeBottom > 0) {
            data.bottomScroll = `${
              info[2].bottom - info[2].top + Number(getSystemInfo().safeBottom)
            }px`;
          }
        }
        if (data.tabActive === 1 && info[1]?.top && info[2]) {
          console.log(
            '11000000=------------',
            getSystemInfo().windowHeight,
            getSystemInfo().screenHeight,
            getSystemInfo().safeBottom,
            getSystemInfo().statusBarHeight,
            getSystemInfo().navigationBarHeight,
            info[1]?.top,
            info[2].height
          );
          data.heightScroll = `${
            getSystemInfo().screenHeight -
            info[1]?.top -
            info[2].height -
            Number(getSystemInfo().safeBottom) -
            Number(getSystemInfo().statusBarHeight) -
            Number(getSystemInfo().navigationBarHeight)
          }px`;
          // #ifdef H5

          data.heightScroll = `${
            getSystemInfo().screenHeight -
            info[1]?.top -
            info[2].height -
            Number(getSystemInfo().safeBottom)
          }px`;
          // #endif
        }
      }
    })
    .exec();
};

onLoad((option: any) => {
  data.id = option.id;
});

onShow(() => {
  const locationInfo = getLocationInfo();
  queryStationDetail(
    {
      stationId: data.id,
      userLat: locationInfo.lat,
      userLng: locationInfo.lng,
      stationLat: 31.942164, // 需要删除
      stationLng: 118.853413, // 需要删除
    },
    data.isLoad
  ).then((res: any) => {
    console.log('res----', res);
    data.isLoad = true;
    data.items = res;
    // 标签
    data.labelStr = [];
    if (res.labelList && res.labelList.length > 0) {
      res.labelList.forEach((item: any) => {
        data.labelStr.push(item.labelName);
      });
    }
    if (res.serviceSetup) {
      const arr = res.serviceSetup.split(',');
      data.labelStr = [...data.labelStr, ...arr];
    }
    data.pics = [];
    //主入口图
    if (res.imgMainEntrance) {
      data.pics.push(res.imgMainEntrance);
    }
    //标志路径
    if (res.imgFlagPath) {
      data.pics.push(res.imgFlagPath);
    }
    //电站全景
    if (res.imgFullView) {
      data.pics.push(res.imgFullView);
    }
    //电桩特写
    if (res.imgPilesFeature) {
      data.pics.push(res.imgPilesFeature);
    }
    //其他图片
    if (res.imgOther) {
      data.pics.push(res.imgOther);
    }

    nextTick(() => {
      getHeight();
    });
  });

  scrollPileRef.value?.resetUpScroll();
});

// tabs点击切换事件
const tapTabs = (type: number) => {
  console.log('data.isLoad----------', data.isLoad);
  if (!data.isLoad) {
    return;
  }
  data.tabActive = type;
  if (type === 2) {
  }
};

// 收藏
const tapCollect = (item: any) => {
  stationCollect(item, '/pages/stationDetails/stationDetails');
};
// 定位
const tapDistance = (item: any) => {
  // #ifdef H5
  locationOpenBtm(item);
  // #endif
  // #ifndef H5
  openLocation(item);
  // #endif
};
// 打开地图弹窗
const locationOpenBtm = (item: any) => {
  locationOpenItem.value = item;
  locationOpenRef.value.open([
    {
      name: '高德地图',
      type: 'gd',
    },
    {
      name: '百度地图',
      type: 'bd',
    },
  ]);
};

// 底部弹窗选择地图
const chooseType = (type: string) => {
  openLocation({ ...locationOpenItem.value, type });
};

// 扫码
const tapCode = () => {
  const token = getToken();
  if (!token) {
    uni.navigateTo({
      url: `/pages/login/login?page=pages/stationDetails/stationDetails`,
    });
    return;
  }
  handleCode(true);
};

//终端列表
const getPile = (extraParams: { pageNum: number; pageSize: number }) => {
  return new Promise(resolve => {
    queryPileList({ stationId: data.id }, extraParams).then((res: any) => {
      console.log('res----', res);
      if (extraParams.pageNum === 1) {
        data.pileList = res.dataList;
      } else {
        data.pileList = [...data.pileList, ...res.dataList];
      }
      resolve({ list: data.pileList, total: res.totalCount });
    });
  });
};
const getPileImg = (item: any) => {
  let img = `${resUrl}station/pile-${Number(item.workStatus)}.png`;
  if (Number(item.workStatus) === 3 && item.soc) {
    img = `${resUrl}station/pile-${Number(item.workStatus)}-1.png`;
  }
  return img;
};
// 终端点击事件-跳转终端详情
const tapPile = (item: any) => {
  uni.navigateTo({
    url: `/pages/stationDetails/pileDetails?id=${item.id}`,
  });
};

//评论列表
const getComment = (extraParams: { pageNum: number; pageSize: number }) => {
  return new Promise(resolve => {
    queryStationComment({ stationId: data.id }, extraParams).then((res: any) => {
      console.log('res----', res);
      if (extraParams.pageNum === 1) {
        data.commentList = res.dataList;
      } else {
        data.commentList = [...data.commentList, ...res.dataList];
      }
      resolve({ list: data.commentList, total: res.totalCount });
    });
  });
};

// 电站图片
const tapImage = () => {
  uni.previewImage({
    urls: data.pics,
    indicator: 'number',
    loop: true,
  });
};

onUnload(() => {
  uni.$emit('returnData', 'stationDetails');
  uni.$emit('collect', { id: data.items.id, status: data.items.collectStatus });
});
// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
// #ifdef H5
:deep(#u-a-p) {
  & > div > div {
    top: 44px !important;
  }
}
// #endif
.station-details {
  position: absolute;
  top: 0;
  box-sizing: border-box;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);
  overflow: hidden;

  .station-header {
    position: relative;

    .labels {
      display: flex;
      flex-wrap: wrap;
      margin: 0 16px 12px 16px;
      font-size: 12px;
      color: #545454;

      .line {
        margin: 0 3px;
      }
    }
  }

  .name {
    width: 270px;
    line-height: 26px;
    margin-top: 12px;
    margin-left: 16px;
    color: #000;
    font-size: 18px;
  }

  .address {
    display: flex;
    // align-items: center;
    width: 270px;
    margin-top: 9px;
    margin-left: 16px;
    color: #545454;
    font-size: 14px;

    .icon-map {
      display: inline-flex;
      margin-right: 7px;
      color: #242424;
      font-size: 16px;
    }

    .text {
      display: inline-flex;
      line-height: 18px;
    }
  }

  .pile {
    display: flex;
    margin-top: 9px;
    margin-left: 16px;
    color: #b5b5b5;
    font-size: 12px;

    .pile-item {
      display: flex;
      align-items: center;
      margin-right: 8px;
      margin-bottom: 12px;
      padding: 2px;
      min-width: 65px;
      height: 17px;
      border: 1px solid #01c68b;
      border-radius: 4px;
      // box-sizing: border-box;

      &.item-interflow {
        border: 1px solid #9859ff;
        // box-sizing: border-box;
      }

      .test1 {
        width: 18px;
        height: 17px;
        line-height: 17px;
        text-align: center;
        color: #fff;
        border-radius: 2px;
      }

      .test1-direct {
        background-color: #01c68b;
      }

      .test1-interflow {
        background-color: #9859ff;
      }

      .test2 {
        margin-left: 4px;
      }

      .test2-direct {
        color: #01c68b;
      }

      .test2-interflow {
        color: #9859ff;
      }
    }
  }

  .collect {
    position: absolute;
    // top: 12px;
    top: 0;
    right: 60px;
    text-align: center;

    .iconfont {
      margin-bottom: 0;
      font-size: 22px;
      color: $uni-color-primary;
    }

    .text {
      line-height: 18px;
      font-size: 10px;
      color: #000;
    }
  }

  .distance {
    position: absolute;
    // top: 12px;
    top: 0;
    right: 16px;
    text-align: center;

    .icon-exclude {
      margin-bottom: 0;
      font-size: 24px;
      color: $uni-color-primary;
    }

    .text {
      line-height: 18px;
      font-size: 10px;
      color: #000;
    }
  }

  .pic-wrap {
    // display: flex;
    margin: 0 0 16px 0;
    height: 70px;
    width: 100vw;
    white-space: nowrap;
    // word-break: keep-all;

    .pic {
      // display: inline-flex;
      display: inline-block;
      width: 148px;
      height: 100%;
      margin: 0 4px;
      border-radius: 4px;

      &:first-child {
        margin-left: 16px;
      }

      &:last-child {
        margin-right: 16px;
      }
    }
  }

  .line {
    width: 100vw;
    height: 10px;
    background-color: #f2f2f2;
  }

  .tabs-wrap {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 42px;
    border-bottom: 1px solid #f2f2f2;
    box-sizing: border-box;

    .tab {
      line-height: 22px;
      font-size: 14px;
      color: #242424;
    }

    .tab-active {
      position: relative;

      &::before {
        background-color: $uni-color-primary;
        bottom: -10px;
        left: calc(50% - 20px);
        content: ' ';
        height: 4px;
        position: absolute;
        width: 40px;
      }
    }
  }

  .bottom-wrap {
    position: absolute;
    display: flex;
    justify-content: space-between;
    bottom: 0;
    width: 100vw;
    height: 62px;
    padding: 0 16px;
    border-top: 1px solid #e6e6e6;
    box-sizing: border-box;
    background-color: #fff;

    .bnt {
      width: 100%;
      height: 44px;
      margin-top: 9px;
      border-radius: 50px;
      border: none;
    }
  }

  .list-wrap {
    display: flex;
    align-items: center;
    position: relative;
    padding: 16px;
    background-color: #fff;
    font-size: 14px;
    color: #545454;
    // border-bottom: 1px solid #f2f2f2;

    .pile-icon {
      position: relative;
      width: 50px;
      height: 66px;
      background-size: 100% 100%;
      margin-right: 12px;

      .text1 {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 80%;
        font-size: 20px;
        color: $uni-color-primary;
      }

      .text2 {
        margin-left: -4px;
        font-size: 12px;
      }
    }

    .pile-wrap {
      width: calc(100% - 62px);
    }

    .pile-name {
      color: #000;
      line-height: 22px;
    }

    .pile-info {
      display: flex;
      justify-content: space-between;
      width: calc(100vw - 50px - 12px - 32px);
      margin-top: 4px;

      .textl {
        color: #858585;
      }

      .textr {
        color: #858585;
      }
    }

    .comment-info {
      display: flex;
      justify-content: space-between;
      align-self: center;
      width: calc(100vw - 32px);
      font-size: 12px;

      .textl {
        line-height: 22px;
        font-size: 14px;
        color: #000;
      }

      .textr {
        line-height: 22px;
        color: #545454;
      }
    }

    .comment-text {
      display: flex;
      justify-self: start;
      width: 100%;
      margin-top: 8px;
      line-height: 18px;
      font-size: 12px;
      word-break: break-all;
    }

    .comment-msg {
      color: #242424;
    }

    .comment-reply {
      padding: 8px;
      color: #858585;
      background-color: #f6f8ff;
    }

    .list-line {
      position: absolute;
      left: 16px;
      right: 16px;
      bottom: 0;
      height: 1px;
      background-color: #f2f2f2;
    }

    .alone-price {
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: 0;
      right: 16px;
      height: 18px;
      width: 60px;
      background-color: $uni-color-primary;
      border-bottom-left-radius: 10px;
      font-size: 10px;
      color: #fff;
    }
  }
}
</style>